package com.xquant.marketdata.curvestrip.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.xquant.common.core.web.controller.BaseController;
import com.xquant.common.core.web.page.TableDataInfo;
import com.xquant.common.log.annotation.Log;
import com.xquant.common.log.enums.BusinessType;
import com.xquant.common.security.utils.ExcelUtil;
import com.xquant.common.security.utils.SecurityUtils;
import com.xquant.marketdata.curvestrip.domain.DivIrCurveDTO;
import com.xquant.marketdata.curvestrip.domain.DivIrCurveStripDTO;
import com.xquant.marketdata.curvestrip.domain.IrCurveSetDTO;
import com.xquant.marketdata.curvestrip.domain.IrCurveStripDTO;
import com.xquant.marketdata.curvestrip.entity.IrCurveDTO;
import com.xquant.marketdata.curvestrip.entity.TdivyieldRatesDTO;
import com.xquant.marketdata.curvestrip.service.DivIrCurveStripService;
import com.xquant.marketdata.utils.CommResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 红利率
 *
 * @author xpp
 */
@RestController
@RequestMapping("divIrCurveStrip")
public class DivIrCurveStripController  extends BaseController {
    @Autowired
    private DivIrCurveStripService divirCurveStripService;
    static String sm = "操作成功";

    /**
     * 查询   TDIVYIELD
     */
    @RequestMapping(value = "/queryDivIrCurveByPage.action")
    @PreAuthorize("@ss.hasPermi('curve:divircurve:divircurveset:list')")
    public TableDataInfo queryIrCurveByPage(@RequestParam Map<String, Object> param) {
        startPage();
        param.put("userId", SecurityUtils.getUserId());
        return getDataTable(divirCurveStripService.queryDivIrCurveByPage(param));
    }

    /**
     * 查询 TIRCURVE_REF_SET
     */
    @RequestMapping(value = "/queryDivIrCurveRefSetByPage.action")
    public PageInfo<Map> queryIrCurveRefSetByPage(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        PageInfo<Map> pageInfo = divirCurveStripService.queryDivIrCurveRefSetByPage(param);
        return pageInfo;
    }

    /**
     * 查询 红利率列表
     */
    @PreAuthorize("@ss.hasPermi('curve:divircurve:divircurvestrip:list')")
    @RequestMapping(value = "/queryDivIrCurveRatesListByPage.action")
    public TableDataInfo queryIrCurveRatesListByPage(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        return  getDataTable(divirCurveStripService.queryDivIrCurveRatesByPage(param));
    }

    /**
     * 查询 红利率图形数据
     */
    @RequestMapping(value = "/queryDivIrCurveRatesByPage.action")
    public CommResponse queryIrCurveRatesByPage(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        return new CommResponse(true,  divirCurveStripService.queryDivIrCurveRatesByPage(param));
    }

    /**
     * 查询 单条TIRCURVE
     */
    @RequestMapping(value = "/getDivIrCurveMx.action")
    public CommResponse getIrCurveMx(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        List<DivIrCurveDTO> list = divirCurveStripService.getDivIrCurveMx(param);
        return new CommResponse(true, list.get(0));
    }

    /**
     * 修改 TIRCURVE
     */
    @RequestMapping(value = "/updateDivIrCurve.action")
    @PreAuthorize("@ss.hasPermi('curve:divircurve:divircurveset:update')")
    public CommResponse updateIrCurve(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        divirCurveStripService.updateDivIrCurve(param);
        return new CommResponse(true, sm);
    }

    /**
     * 新增 TIRCURVE
     */
    @PreAuthorize("@ss.hasPermi('curve:divircurve:divircurveset:add')")
    @RequestMapping(value = "/insertDivIrCurve.action")
    public CommResponse insertIrCurve(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        List<DivIrCurveDTO> list = divirCurveStripService.checkDivIrCurve(param);
        if (list.size() >= 1) {
            return new CommResponse(false, "此红利率曲线已存在，请删除后再新增");
        }
        divirCurveStripService.allocateDivCurve(param);
        divirCurveStripService.insertDivIrCurve(param);
        return new CommResponse(true, sm);
    }

    /**
     * 删除 TIRCURVE
     */
    @RequestMapping(value = "/deleteDivIrCurve.action")
    @PreAuthorize("@ss.hasPermi('curve:divircurve:divircurveset:del')")
    public CommResponse deleteIrCurve(@RequestParam Map<String, Object> param) {
        divirCurveStripService.deleteDivIrCurve(param);
        return new CommResponse(true, sm);
    }

    /**
     * 利率曲线定义查询导出
     */
    @Log(title = "红利信息", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('curve:divircurve:divircurveset:export')")
    @RequestMapping(value = "/export")
    public void exportSet(HttpServletResponse response, @RequestParam Map<String, Object> param) {
        startPage();
        param.put("userId", SecurityUtils.getUserId());
        List<DivIrCurveDTO> list = divirCurveStripService.queryDivIrCurveByPage(param);
        ExcelUtil<DivIrCurveDTO> util = new ExcelUtil<DivIrCurveDTO>(DivIrCurveDTO.class);
        util.exportExcel(response, list, "红利曲线定义");
    }

    /**
     * 修改 TIRCURVE_REF_SET
     */
    @RequestMapping(value = "/updateDivIrCurveRefSet.action")
    public CommResponse updateIrCurveRefSet(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        param.put("endDate", "2050-12-31");
        int ct = divirCurveStripService.queryDivIrCurveRefSetByDate(param);
        divirCurveStripService.deleteDivIrCurveRefSetByDate(param);
        divirCurveStripService.updateDivIrCurveRefSet(param);
        divirCurveStripService.insertDivIrCurveRefSetByDate(param);
        return new CommResponse(true, sm);
    }

    /**
     * 修改 TIRCURVE_RATES
     */
    @RequestMapping(value = "/updateDivIrCurveRates.action")
    @PreAuthorize("@ss.hasPermi('marketdata:DivIrCurve:update')")
    public CommResponse updateIrCurveRates(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        param.put("divTerm",param.get("divTerm").toString().toUpperCase(Locale.ROOT));
        divirCurveStripService.updateDivIrCurveRates(param);
        return new CommResponse(true, sm);
    }

    /**
     * 新增 TIRCURVE_REF_SET
     */
    @RequestMapping(value = "/insertDivIrCurveRefSet.action")
    public CommResponse insertIrCurveRefSet(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        param.put("endDate", "2050-12-31");
        List<Map> list = divirCurveStripService.queryDivIrCurveRefSetByPage(param).getList();
        if (list.size() >= 1) {
            return new CommResponse(false, "此样本点已存在，请删除后再新增!");
        }
        divirCurveStripService.insertDivIrCurveRefSet(param);
        return new CommResponse(true, sm);
    }

    /**
     * 新增 TIRCURVE_Rates
     */
    @RequestMapping(value = "/insertDivIrCurveRates.action")
    @PreAuthorize("@ss.hasPermi('marketdata:DivIrCurve:add')")
    public CommResponse insertIrCurveRates(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
//        param.put("ircCode",param.get("divCode"));
//        param.put("refSetDate",param.get("begDate"));
//        List<DivIrCurveStripDTO> list = divirCurveStripService.queryDivIrCurveRatesByPage(param);
//        if (list.size() >= 1) {
//            return new CommResponse(false, "此曲线期限结构已存在，请删除后再新增!");
//        }
//        param.put("endDate", "2050-12-31");
        param.put("divTerm",param.get("divTerm").toString().toUpperCase(Locale.ROOT));
        divirCurveStripService.insertDivIrCurveRates(param);
        return new CommResponse(true, sm);
    }

    /**
     * 删除 TIRCURVE_REF_SET
     */
    @RequestMapping(value = "/deleteDivIrCurveRefSet.action")
    public CommResponse deleteIrCurveRefSet(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());

        divirCurveStripService.deleteDivIrCurveRefSet(param);
        return new CommResponse(true, sm);
    }

    /**
     * 删除 TIRCURVE_Rates
     */
    @RequestMapping(value = "/deleteDivIrCurveRates.action")
    @PreAuthorize("@ss.hasPermi('marketdata:DivirCurve:delete')")
    public CommResponse deleteIrCurveRates(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());

        divirCurveStripService.deleteDivIrCurveRates(param);
        return new CommResponse(true, sm);
    }

    /**
     * 根据divCode获取DivCurve
     */
    @RequestMapping(value = "/getDivCurveByCode.action")
    public CommResponse getDivCurveByCode(@RequestParam Map<String, Object> param) {
        Boolean flag = false;
        String divCode = (String) param.get("divCode");
        Map map = divirCurveStripService.getDivCurveByCode(divCode);
        if (map == null) {
            flag = true;
        }
        return new CommResponse(true,flag);
    }

    /**
     * 过滤样本点 TIRCURVE_REF_SET
     * todo
     */

    @RequestMapping(value = "/resetDivIrCurveRefSet.action")
    public CommResponse resetIrCurveRefSet(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        //divirCurveStripService.deleteAllIrCurveRefSet(param);
        //divirCurveStripService.filterIrCurveRefSet(param);
        PageInfo<Map> pageInfo = divirCurveStripService.queryFilterDivIrCurveRefSetByPage(param);
        return new CommResponse(true, pageInfo);
    }

    /**
     * 过滤样本点 TIRCURVE_REF_SET
     * todo
     */

    @RequestMapping(value = "/queryFilterDivIrCurveRefSetByPage.action")
    public PageInfo<Map> queryFilterIrCurveRefSetByPage(@RequestParam Map<String, Object> param) {
        param.put("userId", SecurityUtils.getUserId());
        JSONObject jsonObject = JSON.parseObject(param.get("filter").toString());
        param.put("aType", jsonObject.getString("aType"));
        PageInfo<Map> pageInfo = divirCurveStripService.queryFilterDivIrCurveRefSetByPage(param);
        return pageInfo;
    }


    @PreAuthorize("@ss.hasPermi('marketdata:DivIrCurve:import')")
    @PostMapping("/importDivIrCurve")
    public CommResponse importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<TdivyieldRatesDTO> util = new ExcelUtil<TdivyieldRatesDTO>(TdivyieldRatesDTO.class);
        Map<String,Object> importResultMap = util.importExcel(file.getInputStream());
        List<TdivyieldRatesDTO> list = (List<TdivyieldRatesDTO>) importResultMap.get("list");
        HashMap<String, Set<String>> map = new HashMap<>();
        HashSet<String> set = new HashSet<>();
        list.stream().forEach(divIrCurveStripDTO->{
            set.add(divIrCurveStripDTO.getDivCode());
        });
        list.stream().forEach(divIrCurveStripDTO->{
            if(set.contains(divIrCurveStripDTO.getDivCode())){
                if (map.get(divIrCurveStripDTO.getDivCode())==null) {
                    map.put(divIrCurveStripDTO.getDivCode(),new HashSet<String>());
                }
                map.get(divIrCurveStripDTO.getDivCode()).add(divIrCurveStripDTO.getBegDate());
            }
        });
        divirCurveStripService.deleteDivIrCurveList(map);
        list = divirCurveStripService.getLastDivIrCurve(map, list);
        boolean flag = divirCurveStripService.insertDivIrCurveList(list);
        if (!flag) {
            return CommResponse.success("导入失败");
        }
        return CommResponse.success("导入成功");
    }
    @RequestMapping(value = "/updateCurveUserAuthority.action")
    @PreAuthorize("@ss.hasPermi('curve:DivirCurve:allocate')")
    public Object updateCurveUserAuthority(@RequestBody Map<String, Object> params) {
        divirCurveStripService.updateCurveUserAuthority(params);
        return CommResponse.success("修改成功");
    }

    /**
     * 导出曲线分析
     */
    @PreAuthorize("@ss.hasPermi('curve:divirCurve:divircurvestrip:export')")
    @RequestMapping(value = "/exportDivStrip.action")
    public void exportDivStrip(HttpServletResponse response, @RequestParam Map<String, Object> param) {
        List<DivIrCurveStripDTO> list = divirCurveStripService.queryDivIrCurveRatesByPage(param);
        ExcelUtil<DivIrCurveStripDTO> util = new ExcelUtil<DivIrCurveStripDTO>(DivIrCurveStripDTO.class);
        util.exportExcel(response, list, "红利曲线分析");
    }
}
